<!DOCTYPE html>
<html>
<head>
<title>iWhere</title>
<meta charset="utf-8">
<!--script src="http://weapp.googlecode.com/svn/api/weapp.min.js"></script-->
<script src="../../WeApp.js"></script>

<style type="text/css">
body {
    font-size: smaller;
}
label:hover {
    cursor: pointer;
    text-decoration: underline;
}
p {
    padding: 0px;
    margin: 5px;
    text-align: center;
}
#locate {
    cursor: pointer;
    width: 150px;
}
</style>

<script>
IWhere = top.Weiran.Class(WeApp, {
    dictionaries: {
        'en': {
            'bind': 'Bind map',
            'watch': 'Watch position',
            'accurate': 'Enable high accuracy',
            'locate': 'Locate me',
            'unlocate': 'Stop tracking'
        },
        'zh-CN' : {
            'bind': '绑定地图',
            'watch': '跟踪位置',
            'accurate': '启用高精度定位',
            'locate': '开始定位',
            'unlocate': '结束跟踪'
        }
    },
        
    // OpenLayers.Control.Geolocate
    geolocate: null,
    
    // OpenLayers.Layer.Vector
    layer: null,

    initialize: function (options) {
        WeApp.prototype.initialize.apply(this, arguments);
        
        // set language
        top.jQuery('#bindLabel', document).text(this.i18n('bind'));
        top.jQuery('#watchLabel', document).text(this.i18n('watch'));
        top.jQuery('#accurateLabel', document).text(this.i18n('accurate'));
        top.jQuery('#locate', document).val(this.i18n('locate'));
        
        this.geolocate = new top.OpenLayers.Control.Geolocate({
            bind: false,
            watch: false,
            geolocationOptions: {
                enableHighAccuracy: false
            }
        });
        this.getMap().addControl(this.geolocate);
        
        this.layer = new top.OpenLayers.Layer.Vector(this.getTitle());
        this.getMap().addLayer(this.layer);
    },

    run: function () {
        WeApp.prototype.run.apply(this, arguments);
        
        // set geolocate
        this.geolocate.bind = top.jQuery('#bind', document).attr('checked');
        this.geolocate.watch = top.jQuery('#watch', document).attr('checked');;
        this.geolocate.geolocationOptions.enableHighAccuracy = top.jQuery('#accurate', document).attr('checked');;
        
        // add event handlers
        top.jQuery('#bind', document).change(top.Weiran.Function.bind(this.onBind, this));
        top.jQuery('#watch', document).change(top.Weiran.Function.bind(this.onWatch, this));
        top.jQuery('#accurate', document).change(top.Weiran.Function.bind(this.onAccurate, this));
        top.jQuery("#locate", document).click(top.Weiran.Function.bind(this.onLocate, this));
        
        this.geolocate.events.register("locationupdated", this, this.onPosUpdate);
        this.geolocate.events.register("locationfailed", this, this.onPosError);
        this.geolocate.events.register("locationuncapable", this, this.onPosUncapable);
        this.geolocate.events.register("activate", this, this.onActivate);
        this.geolocate.events.register("deactivate", this, this.onDeactivate);
    },

    destroy: function () {
        this.getMap().removeLayer(this.layer);
        this.layer.destroy();
        this.layer = null;
        
        this.getMap().removeControl(this.geolocate);
        this.geolocate.destroy();
        this.geolocate = null;
        
        WeApp.prototype.destroy.apply(this, arguments);
    },
    
    onBind: function(evt) {
        this.geolocate.bind = evt.currentTarget.checked ? true : false;
    },
    
    onWatch: function(evt) {
        this.geolocate.watch = evt.currentTarget.checked ? true : false;
    },
    
    onAccurate: function(evt) {
        this.geolocate.geolocationOptions.enableHighAccuracy = evt.currentTarget.checked ? true : false;
    },
    
    onLocate: function(evt) {
        if (this.geolocate.active) {
            this.geolocate.deactivate();
        } else {
            this.geolocate.activate();
        }
    },
    
    onPosUpdate: function (evt) {
        if (!this.geolocate.watch) {
            this.geolocate.deactivate();
        }
        
        this.layer.removeAllFeatures();
        this.layer.addFeatures([
            new top.OpenLayers.Feature.Vector(
                evt.point,
                {},
                {
                    graphicName: "cross",
                    strokeColor: "red",
                    strokeWidth: 2,
                    fillOpacity: 0,
                    pointRadius: 10
                }
            ),
            new top.OpenLayers.Feature.Vector(
                top.OpenLayers.Geometry.Polygon.createRegularPolygon(
                    new top.OpenLayers.Geometry.Point(evt.point.x, evt.point.y),
                    evt.position.coords.accuracy/2,
                    40,
                    0
                ),
                {},
                {
                    fillColor: 'blue',
                    fillOpacity: 0.1,
                    strokeWidth: 0
                }
            )
        ]);
        
        if (this.geolocate.bind) {
            this.getMap().zoomToExtent(this.layer.getDataExtent());
        }
    },
    
    onPosError: function (evt) {
        this.geolocate.deactivate();
        alert(evt.error);
    },
    
    onPosUncapable: function() {
        // try ip positioning method
        top.Weiran.require([
            'http://j.maxmind.com/app/geoip.js'
        ], top.Weiran.Function.bind(function() {
            var center = new top.OpenLayers.LonLat(
                geoip_longitude(),
                geoip_latitude()
            ).transform(
                this.getMap().displayProjection,
                this.getMap().getProjectionObject()
            );
            
            this.geolocate.events.triggerEvent('locationupdated', {
                position: {
                    coords: {
                        longitude: geoip_longitude(),
                        latitude: geoip_latitude(),
                        accuracy: 50000
                    }
                },
                point: new top.OpenLayers.Geometry.Point(center.lon, center.lat)
            })
        }, this), document);
        
        this.geolocate.deactivate();
    },
    
    onActivate: function() {
        top.jQuery('#locate', document).val(this.i18n('unlocate'));
    },
    
    onDeactivate: function() {
        top.jQuery('#locate', document).val(this.i18n('locate'));
    },

    CLASS_NAME: "IWhere"
});

function main(options) {
    var app = new IWhere(options);
    app.run();
}
</script>
</head>

<body>
    <input type="checkbox" name="bind" id="bind" checked="checked" />
    <label for="bind" id="bindLabel" ></label>
    <br />
    <input type="checkbox" name="watch" id="watch" />
    <label for="watch" id="watchLabel"></label>
    <br />
    <input type="checkbox" name="accurate" id="accurate" />
    <label for="accurate" id="accurateLabel"></label>
    <p><input type="button" id="locate" value="Locate me"/></p>
</body>
</html>
